#!/usr/bin/python

""" tallyDietaryInfo.py
    Pulls info from the DB on the dietary preferences of users

    Tallies info and sends message to designated address """

__author__ = "Dylan J. Sather"
__created__ = "2009-07-14"
__lastEdited__ = "2009-07-14"

import smtplib
import MySQLdb

# Functions
def splitWord(str,list):
    """ Splits str into individual characters; appends each character to list
	Arguments: str - a string
		   list - a list of characters
	Returns: a list of characters """

    for letter in str:
	list.append(letter)
    return list

# Lists for dietary info
canEatList = []
isAList = []

# Connect to the DB and set cursor; fetch result set
db = MySQLdb.connect(host="localhost", user="user", passwd="passwd", db="db")
cursor = tcdb.cursor()

cursor.execute("SELECT canEat, isA \
		FROM users_data \
		INNER JOIN users \
		ON users_data.user_id = users.id")

# Build our lists of dietary preferences
for data in cursor.fetchall():
    splitWord(data[0],canEatList)
    splitWord(data[1],isAList)

# Create message for e-mailing
msg = str(canEatList.count('B')) + " people can eat Beef\n"
msg += str(canEatList.count('P')) + " people can eat Poultry\n"
msg += str(canEatList.count('p')) + " people can eat Pork\n"
msg += str(canEatList.count('v')) + " people can eat Veggies\n"
msg += str(canEatList.count('S')) + " people can eat Sugar Sweets\n"
msg += str(canEatList.count('s')) + " people can eat Nonsugar Sweets\n"
msg += str(canEatList.count('I')) + " people can eat Ice Cream\n"
msg += str(isAList.count('V')) + " people are Vegetarian\n"
msg += str(isAList.count('v')) + " people are Vegan\n"

# Send message
fromAddress = "dietary.info@grinnell.edu"
toAddress = "tc@grinnell.edu"
subject = "Tally of Dietary Info"

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (fromAddress, toAddress, subject, msg)
server = smtplib.SMTP('localhost')
server.sendmail(fromAddress, toAddress, message)
server.quit()

# Close up
cursor.close()
tcdb.close()
